package com.cquprt.Tcp;

import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.extern.slf4j.Slf4j;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.net.SocketTimeoutException;

/**
 * 接收数据的线程
 */
@EqualsAndHashCode(callSuper = true)
@Data
@Slf4j
public class ReceiveThread extends Thread{
    //添加volatile关键字使内存中的值刷新，否则循环中可能不刷新值
    //输入流
    private volatile BufferedInputStream bi;
    //当前端口号
    public volatile int port;
    //输出流
    private volatile BufferedOutputStream bo;
    //读出的数据
    private volatile int len;
    //是否停止
    private volatile boolean stopThread=false;
    @Override
    public void run() {
        log.info("读线程启动");
        byte[] bytes=new byte[1024];
        while (true) {
            //判断是否停止线程
            if (stopThread){
                stopThread=false;
                break;
            }else {
                try {
                    if (bi!=null) {
                        try {
                            len = bi.read(bytes);
                            if (len==-1){
                                break;
                            }
                            System.out.println(port+"本次接收到的数据为："+new String(bytes,0,len));
                            bo.write((port+"端口已收到").getBytes());
                            bo.flush();
                        }catch (SocketTimeoutException e){
                            log.info(port+"长时间未收到信息,开始发送心跳包判断连接是否断开");
                            if (bo!=null){
                                try {
                                    bo.write(0xff);
                                    bo.flush();
                                    log.info(port+"心跳包发送成功,连接未断开");
                                }catch (IOException ignored){
                                    log.info(port+"心跳包发送失败，连接已断开");
                                    break;
                                }
                            }else {
                                break;
                            }
                        }
                    }
                } catch (IOException e) {
                    log.info(e.getMessage());
                    //重置当前停止标志位
                    stopThread=false;
                    //停止主线程
                    TcpTransitMsgString.stopThis=true;
                    log.info(port+"读线程停止");
                    break;
                }
            }
        }
    }
}
